package com.nstskj.study.netty.tcp.netty.protocol.handler.msg.impl;

import com.nstskj.study.netty.tcp.netty.manage.LocalMananger;
import com.nstskj.study.netty.tcp.netty.protocol.endpoint.DeviceEndpoint;
import com.nstskj.study.netty.tcp.netty.protocol.enums.IotDeviceProtocolCmdEnum;
import com.nstskj.study.netty.tcp.netty.protocol.event.RegisterNetDeviceEvent;
import com.nstskj.study.netty.tcp.netty.protocol.handler.msg.AbstractProtocolHandler;
import com.nstskj.study.netty.tcp.netty.protocol.message.in.msg.DeviceRegisterCmdMsg;
import com.nstskj.study.netty.tcp.netty.protocol.message.out.msg.DeviceRegisterOutputNetTcpMessage;
import com.nstskj.study.netty.tcp.netty.protocol.session.NetDeviceSession;
import com.nstskj.study.netty.tcp.netty.protocol.session.base.AbstractSession;
import com.nstskj.study.netty.tcp.netty.protocol.session.enums.SessionStatusEnums;
import com.nstskj.study.netty.tcp.util.TcpSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project nstskj-study-netty-tcp-spring
 * @date 2021/4/20 21:07
 * @Description 设备注册消息处理者
 */
@Slf4j
@Component
public class DeviceRegisterHandler extends AbstractProtocolHandler<DeviceRegisterCmdMsg, DeviceRegisterOutputNetTcpMessage> {

    @Override
    public short supportCmd() {
        return (short) IotDeviceProtocolCmdEnum.DEVICE_REGISTER.getCmd();
    }

    /**
     * 真正的协议处理 ，之类需要自己实现
     *
     * @param abstractInputNetTcpMessage
     * @param session
     * @return
     */
    @Override
    public DeviceRegisterOutputNetTcpMessage doHandlerCmdMsg(DeviceRegisterCmdMsg abstractInputNetTcpMessage, AbstractSession session) {
        //得到设备会话
        NetDeviceSession netDeviceSession = (NetDeviceSession) TcpSessionUtils.getSessionByTcpMessage(abstractInputNetTcpMessage);
        //开始设置设备属性 并更新设备状态
        netDeviceSession.setFactoryId(abstractInputNetTcpMessage.getFactoryId());
        netDeviceSession.setDeviceId(abstractInputNetTcpMessage.getDeviceId());
        netDeviceSession.setDeviceVersion(abstractInputNetTcpMessage.getDeviceVersion());
        netDeviceSession.setUserId(abstractInputNetTcpMessage.getUserId());
        Map<Short, DeviceEndpoint> endpointMap = abstractInputNetTcpMessage.getEndpointMap();
        netDeviceSession.getEndpointMap().putAll(endpointMap);
        //更新状态
        netDeviceSession.setStatus(SessionStatusEnums.RUNING);
        //发布注册事件
        RegisterNetDeviceEvent registerNetDeviceEvent = new RegisterNetDeviceEvent(this, netDeviceSession);
        LocalMananger.INSTANCE.getLocalSpringBeanManager().getApplicationContext().publishEvent(registerNetDeviceEvent);
        DeviceRegisterOutputNetTcpMessage deviceRegisterOutputNetTcpMessage = new DeviceRegisterOutputNetTcpMessage();
        deviceRegisterOutputNetTcpMessage.setStatus((byte) 0X00);
        return deviceRegisterOutputNetTcpMessage;
    }
}
